import React, {useEffect} from "react";
import {getCookieToken} from "@/utils/auth";
import {useLoaderData, useLocation, useNavigate} from "react-router";
import type {MetaProps} from "@/typings/router";

enum ENUM {
    LOGIN = '/login',
    HOME = '/home'
}

const RouterGuard = ({children}: { children: React.ReactNode }): React.ReactNode => {

    const loader = useLoaderData() as MetaProps;
    const {pathname} = useLocation()
    const navigate = useNavigate();
    const token = getCookieToken()
    window.$navigate = navigate;

    document.title = loader?.title ? `${loader.title} - ${import.meta.env.VITE_APP_TITLE || 'React-Admin-Template'}` : 'React-Admin-Template';

    useEffect(() => {
        if (!token && pathname !== ENUM.LOGIN) {
            navigate(`${ENUM.LOGIN}?redirect=${pathname}`, {replace: true})
        } else if (token && pathname === ENUM.LOGIN) {
            navigate(ENUM.HOME)
        }
    }, [loader]);

    return children
}

export default RouterGuard
